﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Aioms.Dtos;
using Aioms.Model;
using Aioms.Models;
using Furion.DynamicApiController;
using Furion.UnifyResult;
using Mapster;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json.Linq;
using SqlSugar;

namespace Aioms.Controllers
{
    /// <summary>
    /// 保养记录
    /// </summary>
    [DynamicApiController]
    public class MtercdController
    {
        private readonly ISqlSugarClient db; // 核心对象：拥有完整的SqlSugar全部功能
        public MtercdController(ISqlSugarClient sqlSugarClient)
        {
            this.db = sqlSugarClient;
        }

        /// <summary>
        /// 保养记录
        /// </summary>
        /// <returns></returns>
        public async Task<IActionResult> PostList([FromForm] long eid, [FromForm] long dvid, [FromForm] int pageIndex = 1, [FromForm] int pageSize = 10) {
            try
            {
                RefAsync<int> total = 0;
                List<TpWorkOrder> workorders = await db.Queryable<TpWorkOrder>()
                .Mapper(async wo =>
                {
                    if (!string.IsNullOrEmpty(wo.Epids))
                    {
                        List<string> realnames = await db.Queryable<Employee>().Where($"FIND_IN_SET(id, '{wo.Epids}')").Select(ep => ep.Realname).ToListAsync();
                        wo.EpRealnames = string.Join(",", realnames.ToArray());
                    }
                })
                .Mapper(wo => wo.TaskPlan, wo => wo.RefId, wo => wo.TaskPlan.Id)
                .Where(wo => wo.Eid == eid)
                .Where(wo => wo.Type == "保养工单")
                .Where(wo => wo.Status == "已完成")
                .Where($"JSON_CONTAINS(CAST(progress as json), JSON_ARRAY({dvid}))")
                .ToPageListAsync(pageIndex, pageSize, total);

                UnifyContext.Fill(new { total = total });

                return new JsonResult(new RESTfulResult<object>
                {
                    StatusCode = 200,
                    Succeeded = true,
                    Data = workorders.Adapt<List<MtercdListDto>>(),
                    Errors = null,
                    Extras = UnifyContext.Take(),
                    Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
                });
            }
            catch (Exception e)
            {
                return new JsonResult(new RESTfulResult<object>
                {
                    StatusCode = -1,
                    Succeeded = false,
                    Data = null,
                    Errors = e.Message,
                    Extras = UnifyContext.Take(),
                    Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
                });
            }
            
        }
    }
}
